package com.ruoyi.withdraw.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.distributor.domain.DistributionUser;
import com.ruoyi.distributor.service.IDistributionUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.withdraw.domain.DistributionWithdraw;
import com.ruoyi.withdraw.service.IDistributionWithdrawService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 提现申请Controller
 * 
 * @author ruoyi
 * @date 2025-10-11
 */
@RestController
@RequestMapping("/ruoyi/withdraw")
public class DistributionWithdrawController extends BaseController
{
    @Autowired
    private IDistributionWithdrawService distributionWithdrawService;

    @Autowired
    private IDistributionUserService distributionUserService;

    /**
     * 查询提现申请列表
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:list')")
    @GetMapping("/list")
    public TableDataInfo list(DistributionWithdraw distributionWithdraw)
    {
        startPage();
        List<DistributionWithdraw> list = distributionWithdrawService.selectDistributionWithdrawList(distributionWithdraw);
        return getDataTable(list);
    }

    /**
     * 导出提现申请列表
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:export')")
    @Log(title = "提现申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DistributionWithdraw distributionWithdraw)
    {
        List<DistributionWithdraw> list = distributionWithdrawService.selectDistributionWithdrawList(distributionWithdraw);
        ExcelUtil<DistributionWithdraw> util = new ExcelUtil<DistributionWithdraw>(DistributionWithdraw.class);
        util.exportExcel(response, list, "提现申请数据");
    }

    /**
     * 获取提现申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:query')")
    @GetMapping(value = "/{withdrawId}")
    public AjaxResult getInfo(@PathVariable("withdrawId") Long withdrawId)
    {
        return success(distributionWithdrawService.selectDistributionWithdrawByWithdrawId(withdrawId));
    }

    /**
     * 新增提现申请
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:add')")
    @Log(title = "提现申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DistributionWithdraw distributionWithdraw)
    {
        return toAjax(distributionWithdrawService.insertDistributionWithdraw(distributionWithdraw));
    }

    /**
     * 修改提现申请
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:edit')")
    @Log(title = "提现申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DistributionWithdraw distributionWithdraw)
    {
        return toAjax(distributionWithdrawService.updateDistributionWithdraw(distributionWithdraw));
    }

    /**
     * 删除提现申请
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:remove')")
    @Log(title = "提现申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{withdrawIds}")
    public AjaxResult remove(@PathVariable Long[] withdrawIds)
    {
        return toAjax(distributionWithdrawService.deleteDistributionWithdrawByWithdrawIds(withdrawIds));
    }

    /**
     * 提交提现申请（分销员使用）
     */
    @Log(title = "提现申请", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitWithdrawApplication(@RequestBody DistributionWithdraw withdrawApplication) {
        try {
            // 获取当前登录用户
            LoginUser loginUser = getLoginUser();
            // 获取当前用户的分销员信息
            DistributionUser distributor = distributionUserService.selectDistributionUserByUserId(loginUser.getUserId());

            // 获取当前登录用户ID作为分销员ID
            Long distributorId = distributor.getDistributorId();
            if (distributorId == null) {
                return AjaxResult.error("无法获取当前用户信息");
            }

            DistributionWithdraw result = distributionWithdrawService.submitWithdrawApplication(
                    distributorId,
                    withdrawApplication.getAmount(),
                    withdrawApplication.getPaymentType(),
                    withdrawApplication.getPaymentAccount(),
                    withdrawApplication.getPaymentName()
            );

            return AjaxResult.success("提现申请提交成功", result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 审核提现申请（管理员使用）
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:audit')")
    @Log(title = "提现申请", businessType = BusinessType.UPDATE)
    @PostMapping("/audit/{withdrawId}")
    public AjaxResult auditWithdrawApplication(@PathVariable Long withdrawId,
                                               @RequestParam String auditStatus,
                                               @RequestParam(required = false) String auditRemark) {
        try {
            // 获取当前登录用户ID作为审核人ID
            Long auditorId = SecurityUtils.getUserId();
            boolean result = distributionWithdrawService.auditWithdrawApplication(
                    withdrawId, auditStatus, auditRemark, auditorId);

            if (result) {
                return AjaxResult.success("审核操作成功");
            } else {
                return AjaxResult.error("审核操作失败");
            }
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 执行打款操作（管理员使用）
     */
    @PreAuthorize("@ss.hasPermi('ruoyi:withdraw:payment')")
    @Log(title = "提现申请", businessType = BusinessType.UPDATE)
    @PostMapping("/executePayment/{withdrawId}")
    public AjaxResult executePayment(@PathVariable Long withdrawId) {
        try {
            boolean result = distributionWithdrawService.executePayment(withdrawId);

            if (result) {
                return AjaxResult.success("打款操作成功");
            } else {
                return AjaxResult.error("打款操作失败");
            }
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 查询当前分销员的提现记录
     */
    @GetMapping("/my")
    public TableDataInfo getMyWithdrawList() {
        try {
            Long distributorId = SecurityUtils.getUserId();
            if (distributorId == null) {
                return getDataTable(null);
            }

            List<DistributionWithdraw> list = distributionWithdrawService.selectWithdrawListByDistributorId(distributorId);
            return getDataTable(list);
        } catch (Exception e) {
            return getDataTable(null);
        }
    }
}
